{{/* Function to return a formatted address given a semantic address. */}}

{{/* Check for valid site config. */}}
{{ if not site.Data.address_formats }}{{errorf "Address formats missing from `data/address_formats.toml`!"}}{{end}}

{{ $page := . }}
{{ $address := .address }}
{{ $format_name := $page.Params.address_format | default site.Params.locale.address_format | default "en-us" }}

{{ if not (isset site.Data.address_formats $format_name) }}{{ errorf "Address format `%s` missing from `data/address_formats.toml`!" $format_name }}{{end}}

{{ $format := index site.Data.address_formats $format_name }}
{{ $address_display := slice }}

{{ range $k, $v := $format.order }}
  {{ if eq $v "street" | and $address.street }}{{$address_display = $address_display | append (transform.HTMLEscape $address.street) | append (index $format.delimiters $k | default "") }}{{end}}
  {{ if eq $v "city" | and $address.city }}{{$address_display = $address_display | append (transform.HTMLEscape $address.city) | append (index $format.delimiters $k | default "") }}{{end}}
  {{ if eq $v "region" | and $address.region }}{{$address_display = $address_display | append (transform.HTMLEscape $address.region) | append (index $format.delimiters $k | default "") }}{{end}}
  {{ if eq $v "postcode" | and $address.postcode }}{{$address_display = $address_display | append (transform.HTMLEscape $address.postcode) | append (index $format.delimiters $k | default "") }}{{end}}
  {{ if eq $v "country" | and $address.country }}{{$address_display = $address_display | append (transform.HTMLEscape $address.country) | append (index $format.delimiters $k | default "") }}{{end}}
{{end}}

{{ return safeHTML (delimit $address_display "") }}
